from odoo import models, api


class SbMESWarehouse(models.Model):
    _inherit = 'stock.warehouse'

    def cron_all(self):
        records = self.env['stock.location'].sudo().search([('id', 'in', [8, 17])])
        for rec in records:
            rec.warehouse_upload_mes_l()

    def warehouse_upload_mes_l(self):
        """
        目前odoo系统，仓库都创建在了库位上，暂时给 wtt/库存和wtt/生产前两个库位，作为mes的仓库，方便领料使用
        """
        warehouse_list = []
        for record in self:
            warehouse_list.append({
                "org_id": "0001",
                "store_code": record.barcode,  # 仓库编码
                "store_name": record.name,  # 仓库名称
                "store_type": 1,  # 仓库类型  1：良品仓 2：不良品仓 3：报废仓 4：待检仓
                "ppt_type": 1,  # 属性类别 1：物料类型 2：其他资产类
                "is_virtual": "N",  # 虚拟仓 是-Y 否-N 默认 N
                "is_bond": "N",  # 保税 是-Y 否-N 默认 N
                "is_line_edge_store": "N",  # 线边仓 是-Y 否-N 默认 N
                "erp_store_code": record.barcode,  # ERP仓库编码
                "is_valid": "Y",  # 启用状态
                "remark": "0"  # 备注
            })
        data = {
            "docType": "BS_STORE",
            "updateType": "UPDATE",
            "data": warehouse_list
        }
        self.env['s.mes.upload'].upload_data(data=data)

    @api.model_create_multi
    def create(self, vals_list):
        result = super().create(vals_list)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            for rec in result:
                rec.with_delay().warehouse_upload_mes()
        return result

    def write(self, vals):
        res = super().write(vals)
        mes_enabled = self.env['s.api.config_parameter'].search([('s_key', '=', 'mes.enabled')], limit=1).s_value
        if mes_enabled:
            self.with_delay().warehouse_upload_mes()
        return res

    def warehouse_upload_mes(self):
        """
        仓库上传 MES 系统
        """
        warehouse_list = []
        for record in self:
            warehouse_list.append({
                "org_id": "0001",
                "store_code": record.code,  # 仓库编码
                "store_name": record.name,  # 仓库名称
                "store_type": 1,  # 仓库类型  1：良品仓 2：不良品仓 3：报废仓 4：待检仓
                "ppt_type": 1,  # 属性类别 1：物料类型 2：其他资产类
                "is_virtual": "N",  # 虚拟仓 是-Y 否-N 默认 N
                "is_bond": "N",  # 保税 是-Y 否-N 默认 N
                "is_line_edge_store": "N",  # 线边仓 是-Y 否-N 默认 N
                "erp_store_code": record.code,  # ERP仓库编码
                "is_valid": "Y",  # 启用状态
                "remark": "0"  # 备注
            })
        data = {
            "docType": "BS_STORE",
            "updateType": "UPDATE",
            "data": warehouse_list
        }
        self.env['s.mes.upload'].upload_data(data=data)
